from PIL import Image
import numpy as np
from pkg import GenName, DownloadImageByUrl
import shutil
import time
import os
import requests
from io import BytesIO

def GetImageArrd(url, mode='RGB'):
    resp = requests.get(url)
    ImageArr = Image.open(BytesIO(resp.content))
    return ImageArr, "ok"

def GetImageArr(url):
      # 根据图片URL用于人脸识别
      # 使用生成的名字下载图片在本地
      StorePath = StoreAndDel()
      try:
          state = DownloadImageByUrl(url, StorePath)
      except:
          return [], "url cant load photo"
      if state != 200 :
          return [], "can't load photo"
      # 从下载好的图片读取信息成 array
      try:
          ImageArr = LoadImage2Array(StorePath)
      except:
          return [], "loaded photo cant read,becase this is nil photo!"
      return ImageArr, "ok" 

def LoadImage2Array(name, mode='RGB'):
      fp = open(name,'rb')
      img = Image.open(fp)

      if mode:
            img = img.convert(mode)
      fp.close()
      return np.array(img)


def StoreAndDel():
      name = GenName() 
      hour = int(time.time()) // 600
      path = "./image/" + str(hour)
      CreateFolder(path)
      StorePath = path + "/" + name + ".jpg" # 后期调整成从配置文件读取路径
      return StorePath

def CreateFolder(folder_name):
      result_data = 0
      folder_name_exist = os.path.exists(folder_name)
      if not folder_name_exist:
            DeleteFolder("./image/")
            os.makedirs(folder_name)
            result_data = 1
      return result_data

def DeleteFolder(path):
      shutil.rmtree(path)

if __name__ == '__main__':
    GetImageArrDri("https://imagepphcloud.thepaper.cn/pph/image/110/252/59.jpg")
